from flask import Blueprint, jsonify, request
from app.models.nav_structure import NavStructure
import os
import json

nav_bp = Blueprint('nav', __name__)
nav_structure = NavStructure()

# 确保数据目录存在
os.makedirs('data/dashboards', exist_ok=True)

# 仪表盘结构文件路径
DASHBOARD_STRUCTURE_FILE = os.path.join('data', 'dashboard_structure.json')
# 导航结构文件路径
NAV_STRUCTURE_FILE = os.path.join('data', 'nav_structure.json')

# 确保仪表盘结构文件存在
if not os.path.exists(DASHBOARD_STRUCTURE_FILE):
    with open(DASHBOARD_STRUCTURE_FILE, 'w', encoding='utf-8') as f:
        json.dump([], f, ensure_ascii=False, indent=2)

@nav_bp.route('/structure', methods=['GET'])
def get_nav_structure():
    """获取导航栏结构"""
    try:
        data = nav_structure.get_structure()
        return jsonify({
            'code': 0,
            'message': 'success',
            'data': data
        })
    except Exception as e:
        return jsonify({
            'code': 1,
            'message': str(e)
        }), 500

@nav_bp.route('/structure', methods=['POST'])
def save_nav_structure():
    """保存导航栏结构"""
    try:
        data = request.get_json()
        if not data or 'structure' not in data:
            return jsonify({
                'code': 1,
                'message': '无效的请求数据'
            }), 400
        
        structure = data['structure']
        if not nav_structure.validate_structure(structure):
            return jsonify({
                'code': 1,
                'message': '导航栏结构格式无效'
            }), 400
        
        if nav_structure.save_structure(structure):
            return jsonify({
                'code': 0,
                'message': 'success'
            })
        else:
            return jsonify({
                'code': 1,
                'message': '保存失败'
            }), 500
    except Exception as e:
        return jsonify({
            'code': 1,
            'message': str(e)
        }), 500

# 获取仪表板目录结构
@nav_bp.route('/dashboard/structure', methods=['GET'])
def get_dashboard_structure():
    print("获取仪表板目录结构")
    try:
        file_path = os.path.join('data', 'dashboard_structure.json')
        if os.path.exists(file_path):
            with open(file_path, 'r', encoding='utf-8') as f:
                structure = json.load(f)
            return jsonify({
                'code': 0,
                'message': '获取成功',
                'data': structure
            })
        else:
            return jsonify({
                'code': 0,
                'message': '文件不存在',
                'data': []
            })
    except Exception as e:
        return jsonify({
            'code': 1,
            'message': f'获取目录结构失败: {str(e)}',
            'data': None
        }), 500

# 保存仪表板目录结构
@nav_bp.route('/dashboard/structure', methods=['POST'])
def save_dashboard_structure():
    try:
        data = request.json
        if not data or 'structure' not in data:
            return jsonify({
                'code': 1,
                'message': '无效的请求数据',
                'data': None
            }), 400

        file_path = os.path.join('data', 'dashboard_structure.json')
        
        # 确保目录存在
        os.makedirs(os.path.dirname(file_path), exist_ok=True)
        
        # 保存结构
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(data['structure'], f, ensure_ascii=False, indent=2)
        
        return jsonify({
            'code': 0,
            'message': '保存成功',
            'data': None
        })
    except Exception as e:
        return jsonify({
            'code': 1,
            'message': f'保存目录结构失败: {str(e)}',
            'data': None
        }), 500

# 仪表盘数据API
@nav_bp.route('/dashboard/<dashboard_id>', methods=['GET'])
def get_dashboard_data(dashboard_id):
    try:
        dashboard_file = os.path.join('data', 'dashboards', f'{dashboard_id}.json')
        if not os.path.exists(dashboard_file):
            return jsonify({
                'code': 1,
                'message': 'Dashboard not found'
            })
        with open(dashboard_file, 'r', encoding='utf-8') as f:
            data = json.load(f)
        return jsonify({
            'code': 0,
            'message': 'success',
            'data': data
        })
    except Exception as e:
        return jsonify({
            'code': 1,
            'message': str(e)
        })

@nav_bp.route('/dashboard/<dashboard_id>', methods=['POST'])
def save_dashboard_data(dashboard_id):
    try:
        data = request.get_json()
        dashboard_dir = os.path.join('data', 'dashboards')
        if not os.path.exists(dashboard_dir):
            os.makedirs(dashboard_dir)
        dashboard_file = os.path.join(dashboard_dir, f'{dashboard_id}.json')
        with open(dashboard_file, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        return jsonify({
            'code': 0,
            'message': 'success'
        })
    except Exception as e:
        return jsonify({
            'code': 1,
            'message': str(e)
        })

@nav_bp.route('/dashboard/<dashboard_id>', methods=['DELETE'])
def delete_dashboard(dashboard_id):
    try:
        dashboard_file = os.path.join('data', 'dashboards', f'{dashboard_id}.json')
        if os.path.exists(dashboard_file):
            os.remove(dashboard_file)
        return jsonify({
            'code': 0,
            'message': 'success'
        })
    except Exception as e:
        return jsonify({
            'code': 1,
            'message': str(e)
        }) 